package cn.xiaoliu.hrm.service.impl;

import cn.xiaoliu.hrm.config.RabbitMqConfig;
import cn.xiaoliu.hrm.constant.CourseConstant;
import cn.xiaoliu.hrm.doc.CourseDoc;
import cn.xiaoliu.hrm.domain.Course;
import cn.xiaoliu.hrm.domain.CourseDetail;
import cn.xiaoliu.hrm.domain.CourseMarket;
import cn.xiaoliu.hrm.domain.CourseType;
import cn.xiaoliu.hrm.dto.CourseDto;
import cn.xiaoliu.hrm.feign.CourseDocFeignClient;
import cn.xiaoliu.hrm.mapper.CourseDetailMapper;
import cn.xiaoliu.hrm.mapper.CourseMapper;
import cn.xiaoliu.hrm.mapper.CourseMarketMapper;
import cn.xiaoliu.hrm.mapper.CourseTypeMapper;
import cn.xiaoliu.hrm.query.CourseDocQuery;
import cn.xiaoliu.hrm.service.ICourseService;
import cn.xiaoliu.hrm.util.AjaxResult;
import cn.xiaoliu.hrm.util.ValidUtils;
import cn.xiaoliu.hrm.vo.UserInfoVo;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.validation.Valid;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xiaoliu
 * @since 2021-12-20
 */
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements ICourseService {
    @Autowired
    private CourseMapper courseMapper;
    @Autowired
    private CourseDetailMapper detailMapper;
    @Autowired
    private CourseMarketMapper marketMapper;
    @Autowired
    private CourseTypeMapper typeMapper;
    @Autowired
    private CourseDocFeignClient docFeignClient;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public AjaxResult saveCourse(@Valid CourseDto dto) {
        //获取当前的用户信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String name = authentication.getName();
        String key = "userinfo"+name;
        Object obj = redisTemplate.opsForValue().get(key);
        UserInfoVo userInfo = JSON.parseObject(JSON.toJSONString(obj), UserInfoVo.class);
        System.err.println(userInfo);

        /**
         * 三张表是一对一的关系，而且里面都没有各自的外键，所有我们使用共享主键来关联
         * 先保存course表，再返回自增主键id用来保存详情表和市场信息表
         */
        //保存course
        Course course = dto.getCourse();
        course.setTenantId(userInfo.getTid());
        course.setTenantName(userInfo.getCompanyName());
        course.setUserName(userInfo.getEmpName());
        course.setUserId(userInfo.getEmpId());
        courseMapper.insert(course);

        //保存市场信息表
        CourseMarket courseMarket = dto.getCourseMarket();
        courseMarket.setId(course.getId());
        marketMapper.insert(courseMarket);

        //保存详情表
        CourseDetail courseDetail = dto.getCourseDetail();
        courseDetail.setId(course.getId());
        detailMapper.insert(courseDetail);

        return AjaxResult.me();
    }
    //课程上线
    @Override
    public AjaxResult onLineCourse(List<Long> ids) {
        /**
         * 先保存到es.然后再修改状态
         */
        ValidUtils.assertNotNull(ids,"未选中课程,请重新选择！" );
        List<Course> courses = courseMapper.selectBatchIds(ids);
        AjaxResult result = null;
        for(Course course:courses) {
            CourseDoc courseDoc = courseToDoc(course);
            CourseType courseType = typeMapper.selectById(course.getCourseTypeId());
            courseDoc.setCourseTypeName(courseType.getName());
            //保存到es
             result = docFeignClient.courseOnline(courseDoc);
            if (result.isSuccess()){
                //成功过后修改状态
                course.setStatus(CourseConstant.ON_LINE);
                courseMapper.updateById(course);
                /**
                 * 调用消息队列将上线消息放入队列然后另外一个服务监听调用短信，邮件，站内信发送信息
                 */
                rabbitTemplate.convertAndSend(RabbitMqConfig.COURSE_ONLINE_NOTICE_EXCHANGE, "message.sms",course.getName());
                rabbitTemplate.convertAndSend(RabbitMqConfig.COURSE_ONLINE_NOTICE_EXCHANGE, "message.system",course.getName());
                rabbitTemplate.convertAndSend(RabbitMqConfig.COURSE_ONLINE_NOTICE_EXCHANGE, "message.email",course.getName());
            }else {
                return result;
            }
        }
        return result;

    }

    //课程下线
    @Override
    public AjaxResult offLineCourse(List<Long> ids) {
        ValidUtils.assertNotNull(ids,"未选中课程,请重新选择！" );
        List<Course> courses = courseMapper.selectBatchIds(ids);
        AjaxResult result = null;
        for(Course course:courses) {
            result = docFeignClient.courseOffline(course.getId());
            if (result.isSuccess()){
                course.setStatus(CourseConstant.OFF_LINE);
                courseMapper.updateById(course);
            }else {
                return result;
            }
        }
        return result;
    }

    /**
     * 全文检索实现分页和排序
     * @param docQuery
     * @return
     */
    @Override
    public AjaxResult queryCourses(CourseDocQuery docQuery) {
        AjaxResult result = docFeignClient.queryCourses(docQuery);
        return result;
    }

    //封装了一个方法将数据保存到es里面
    private CourseDoc courseToDoc(Course course) {
        CourseDoc courseDoc = new CourseDoc();
        BeanUtils.copyProperties(course,courseDoc );
        CourseDetail courseDetail = detailMapper.selectById(course.getId());
        BeanUtils.copyProperties(courseDetail,courseDoc );
        CourseMarket courseMarket = marketMapper.selectById(course.getId());
        BeanUtils.copyProperties(courseMarket,courseDoc);
        return courseDoc;
    }
}
